package cn.hh.ymcc.userdetails;

import cn.hh.ymcc.domain.Login;
import cn.hh.ymcc.domain.Permission;
import cn.hh.ymcc.dto.LoginInfoDto;
import cn.hh.ymcc.enums.GlobalExceptionCode;
import cn.hh.ymcc.mapper.PermissionMapper;
import cn.hh.ymcc.service.ILoginService;
import cn.hh.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  自定义的从数据库查询登录信息
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private PermissionMapper permissionMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        EntityWrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username",username);

        Login login = loginService.selectOne(wrapper);
        AssertUtil.isNotNull(login, GlobalExceptionCode.LOGIN_USER_IS_NULL_ERROR.getMessage());

        List<Permission> permissions = permissionMapper.loadPermissionsByLoginId(login.getId());
        List<GrantedAuthority> authorities = permissions.stream().map(p -> new SimpleGrantedAuthority(p.getSn())).collect(Collectors.toList());

        LoginInfoDto loginInfoDto = new LoginInfoDto(login.getId(),login.getUsername());
        return new User(
                JSON.toJSONString(loginInfoDto),
                login.getPassword(),
                login.getEnabled(),
                login.getAccountNonExpired(),
                login.getCredentialsNonExpired(),
                login.getAccountNonLocked(),
                authorities);
    }
}
